<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="工单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入工单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-select
            v-model="queryParams.productName"
            placeholder="请选择产品名称"
            filterable
            clearable
            @change="handleQuery"
        >
          <el-option
              v-for="product in productsList"
              :key="product.productId"
              :label="product.productName"
              :value="product.productName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划开始时间" prop="plannedStartTime">
        <el-date-picker clearable
          v-model="queryParams.plannedStartTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择计划开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划结束时间" prop="plannedEndTime">
        <el-date-picker clearable
          v-model="queryParams.plannedEndTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择计划结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="优先级" prop="priority" label-width="100px">
        <el-select
            v-model="queryParams.priority"
            placeholder="请选择优先级"
            clearable
            @change="handleQuery"
            style="width: 130px;"

        >
          <el-option label="高" value="1"></el-option>
          <el-option label="中" value="2"></el-option>
          <el-option label="低" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="status" label-width="100px">
        <el-select
            v-model="queryParams.status"
            placeholder="请选择工单状态"
            clearable
            @change="handleQuery"
            style="width: 130px;"

        >
          <el-option label="创建" value="1"></el-option>
          <el-option label="生产中" value="2"></el-option>
          <el-option label="暂停" value="3"></el-option>
          <el-option label="待质检" value="4"></el-option>
          <el-option label="完成" value="5"></el-option>
          <el-option label="取消" value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产线ID" prop="lineId">
        <el-input
          v-model="queryParams.lineId"
          placeholder="请输入产线ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['workorder-service:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['workorder-service:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workorder-service:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['workorder-service:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工单ID" align="center" prop="id" />
      <el-table-column label="工单号" align="center" prop="orderNumber" />
      <el-table-column label="产品ID" align="center" prop="productId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="计划数量" align="center" prop="plannedQuantity" />
      <el-table-column label="实际数量" align="center" prop="actualQuantity" />
      <el-table-column label="计划开始时间" align="center" prop="plannedStartTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.plannedStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="plannedEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.plannedEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际开始时间" align="center" prop="actualStartTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.actualStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.actualEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="status" >
      <template #default="{ row }">
        {{ statusDict[row.status] || '未知' }}
      </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级">
        <template #default="{ row }">
          {{ priorityDict[row.priority] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="产线ID" align="center" prop="lineId" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['workorder-service:orders:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['workorder-service:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="抽检" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              :type="scope.row.status === 4 ? 'primary' : 'text'"
              :disabled="scope.row.status !== 4"
              :class="{'inspection-btn': scope.row.status === 4}"
              icon="Check"
              @click="handleInspection(scope.row)"
          >
            抽检
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="工单号" prop="orderNumber">-->
        <!--          <el-input v-model="form.orderNumber" placeholder="工单号为WO+时间+序列号" />-->
        <!--        </el-form-item>-->
        <el-form-item label="产品名称" prop="productName">
          <el-select
              v-model="form.productName"
              placeholder="请选择产品名称"
              filterable
              clearable
              @change="handleProductNameChange"
          >
            <el-option
                v-for="product in productsList"
                :key="product.productId"
                :label="product.productName"
                :value="product.productName"
            />
          </el-select>
        </el-form-item>

        <!-- 隐藏 productId（仍然绑定，但不显示） -->
        <el-input v-show="false" v-model="form.productId" />
        <el-form-item label="计划数量" prop="plannedQuantity">
          <el-input v-model="form.plannedQuantity" placeholder="请输入计划数量" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="plannedStartTime">
          <el-date-picker clearable
            v-model="form.plannedStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="plannedEndTime">
          <el-date-picker clearable
            v-model="form.plannedEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际开始时间" prop="actualStartTime">
          <el-date-picker clearable
            v-model="form.actualStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择实际开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际结束时间" prop="actualEndTime">
          <el-date-picker clearable
            v-model="form.actualEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择实际结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="优先级:" prop="priority">
          <el-select
              v-model="form.priority"
              placeholder="请选择优先级"
              clearable
              @change="handleQuery"
              style="width: 130px;"

          >
            <el-option label="高" value="1"></el-option>
            <el-option label="中" value="2"></el-option>
            <el-option label="低" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态:" prop="status">
          <el-select
              v-model="form.status"
              placeholder="请选择优先级"
              clearable
              @change="handleQuery"
              style="width: 130px;"

          >
            <el-option label="创建" value="1"></el-option>
            <el-option label="生产中" value="2"></el-option>
            <el-option label="暂停" value="3"></el-option>
            <el-option label="待质检" value="4"></el-option>
            <el-option label="完成" value="5"></el-option>
            <el-option label="取消" value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产线ID" prop="lineId">
          <el-input v-model="form.lineId" placeholder="请输入产线ID" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">

import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/workorder-service/orders"
import {listProducts} from "@/api/base-data-service/products.js";
import useUserStore from "@/store/modules/user.js";
const { proxy } = getCurrentInstance()
const productsList = ref([])
const ordersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const priorityDict = {
  1: '高',
  2: '中',
  3: '低',
  // 或者其他你的业务映射
}
const statusDict = {
  1: '创建',
  2: '生产中',
  3: '暂停',
  4:'待质检' ,
  5:'完成',
  6:'取消'

}
import { useRouter } from 'vue-router'

// 在setup中获取router实例
const router = useRouter()
// 抽检按钮操作
function handleInspection(row) {
  proxy.$modal.confirm(`确认要对工单 ${row.orderNumber} 进行抽检吗?`).then(() => {
    // 跳转到抽检页面
    router.push({
      path: '/workorder-service/orders/check',
      query: {
        orderId: row.id,
        orderNumber: row.orderNumber,
        actualQuantity: row.actualQuantity,
        productName: row.productName
      }
    })
  }).catch(() => {});
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNumber: null,
    productId: null,
    productName: null,
    plannedQuantity: null,
    actualQuantity: null,
    plannedStartTime: null,
    plannedEndTime: null,
    actualStartTime: null,
    actualEndTime: null,
    status: null,
    priority: null,
    workshopId: null,
    workshopName: null,
    lineId: null,
    lineName: null,
  },
  rules: {
    // orderNumber: [
    //   { required: true, message: "工单号不能为空", trigger: "blur" }
    // ],
    productId: [
      { required: true, message: "产品ID不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    plannedQuantity: [
      { required: true, message: "计划数量不能为空", trigger: "blur" }
    ],
    plannedStartTime: [
      { required: true, message: "计划开始时间不能为空", trigger: "blur" }
    ],
    plannedEndTime: [
      { required: true, message: "计划结束时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "工单状态：1-创建，2-生产中，3-暂停，4-完成，5-取消不能为空", trigger: "change" }
    ],
    priority: [
      { required: true, message: "优先级：1-高，2-中，3-低不能为空", trigger: "blur" }
    ],
    // workshopId: [
    //   { required: true, message: "车间ID不能为空", trigger: "blur" }
    // ],
    // workshopName: [
    //   { required: true, message: "车间名称不能为空", trigger: "blur" }
    // ],
    createBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})
const userStore = useUserStore()
const username = userStore.name
const { queryParams, form, rules } = toRefs(data)
console.log(userStore.roles)

/** 查询工单管理列表 */
function getList() {
  loading.value = true
  listOrders(queryParams.value).then(response => {
    console.log(response)
    ordersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getProductList() {
  loading.value = true;
  listProducts(queryParams.value).then(response => {
    productsList.value = response.rows;
    console.log(productsList)
    const productDict = {};
    response.rows.forEach(product => {
      productDict[product.productId] = product.productName;
    });

    // 现在 productDict 就是你要的数据字典
    console.log(productDict); // 例如: {1: "产品A", 2: "产品B"}
  });
}
function handleProductNameChange(selectedName) {
  if (!selectedName) {
    form.productId = ''; // 清空时也清空 ID
    console.log("清空Id")
    return;
  }

  // 遍历 productsList 找到匹配的 productId
  const selectedProduct = productsList.value.find(
      (product) => product.productName === selectedName
  );

  if (selectedProduct) {
    console.log("设置Id "+selectedProduct.productId)
    form.value.productId = selectedProduct.productId; // 自动设置 ID
  }
}
getProductList();
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNumber: null,
    productId: null,
    productName: null,
    plannedQuantity: null,
    actualQuantity: null,
    plannedStartTime: null,
    plannedEndTime: null,
    actualStartTime: null,
    actualEndTime: null,
    status: null,
    priority: null,
    workshopId: null,
    workshopName: null,
    lineId: null,
    lineName: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("ordersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加工单管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改工单管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        form.value.createBy=username
        addOrders(form.value).then(response => {
          console.log(response)
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除工单管理编号为"' + _ids + '"的数据项？').then(function() {
    return delOrders(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('workorder-service/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style>
.inspection-btn {
  color: #409EFF;
}
</style>